<template>
  <el-main class="bg table_wrap comtabel_t">
    <el-form label-position="right" :model="query" class="form p_4" label-width="120">
      <el-row class="rows row1">
        <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
          <el-form-item label="民宿名称">
            <el-input v-model="query.name_of_homestay"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
          <el-form-item label="民宿位置">
            <el-input v-model="query.location_of_homestay"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="rows row2">
        <el-col :xs="24" :sm="24" :lg="24" class="search_btn_wrap search_btns">
          <el-col :xs="24" :sm="10" :lg="8" class="search_btn_1 search_btn_wrap_1 btns">
            <el-button type="primary" @click="search()" class="search_btn_find">查询</el-button>
            <el-button @click="reset()" style="margin-right: 74px;" class="search_btn_reset">重置</el-button>
            <el-button v-if="$check_action('/room_cleaning/table','del') || $check_action('/room_cleaning/view','del')"
                       class="search_btn_del" type="danger" @click="delInfo()">删除
            </el-button>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="list" @selection-change="selectionChange" @sort-change="$sortChange" style="width: 100%"
              id="dataTable">
      <el-table-column fixed type="selection" tooltip-effect="dark" width="55"/>
      <el-table-column prop="business_user" @sort-change="$sortChange" label="商家用户"
                       v-if="$check_field('get','business_user')">
        <template slot-scope="scope">
          {{ get_user_business_user(scope.row['business_user']) }}
        </template>
      </el-table-column>
      <el-table-column prop="name_of_homestay" @sort-change="$sortChange" label="民宿名称"
                       v-if="$check_field('get','name_of_homestay')"/>
      <el-table-column prop="location_of_homestay" @sort-change="$sortChange" label="民宿位置"
                       v-if="$check_field('get','location_of_homestay')"/>
      <el-table-column prop="state" @sort-change="$sortChange" label="状态"/>
      <el-table-column prop="cleaning_the_user" @sort-change="$sortChange" label="打扫用户"
                       v-if="$check_field('get','cleaning_the_user')">
        <template slot-scope="scope">
          {{ get_user_cleaning_the_user(scope.row['cleaning_the_user']) }}
        </template>
      </el-table-column>
      <el-table-column prop="cleaning_time" @sort-change="$sortChange" label="打扫时间"
                       v-if="$check_field('get','cleaning_time')">
        <template slot-scope="scope">
          {{ $toTime(scope.row["cleaning_time"], "yyyy-MM-dd") }}
        </template>
      </el-table-column>
      <el-table-column prop="cleaning_remarks" @sort-change="$sortChange" label="打扫备注"
                       v-if="$check_field('get','cleaning_remarks')"/>
      <!-- 新增：图片展示列 -->
      <el-table-column prop="img" label="打扫图片">
        <template slot-scope="scope">
          <img v-if="scope.row['img']" :src="$fullUrl(scope.row['img'])" class="table-img"/>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column sortable prop="create_time" label="创建时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["create_time"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="update_time" label="更新时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["update_time"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作"
                       v-if="$check_action('/room_cleaning/table','set') || $check_action('/room_cleaning/view','set') || $check_action('/room_cleaning/view','get')">
        <template slot-scope="scope">
          <div class="view_a">
            <router-link class="e-button el-button--small is-plain el-button--success" style="margin: 5px !important;"
                         v-if="$check_action('/room_cleaning/table','set') || $check_action('/room_cleaning/view','set') || $check_action('/room_cleaning/view','get')"
                         :to="'./view?' + field + '=' + scope.row[field]"
                         size="small">
              <span>详情</span>
            </router-link>
            <!-- 修改：在 el-upload 中显式传递 row 数据 -->
            <el-upload class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" action="" :http-request="(param) => uploadroomimg(param, scope.row)">
              <span>打扫图片</span>
            </el-upload>
            <!-- 修改：点击“打扫完成”按钮时弹出输入框 -->
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="showCleaningRemarkDialog(scope.row)" v-if="scope.row.state==='待打扫'">
              <span>打扫完成</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="mt text_center">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="query.page" :page-sizes="[7, 10, 30, 100]" :page-size="query.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="count">
      </el-pagination>
    </div>
    <!-- /分页器 -->
    <!-- 新增：打扫备注弹窗 -->
    <el-dialog title="打扫备注" :visible.sync="cleaningRemarkDialogVisible" width="30%">
      <el-input v-model="cleaningRemark" placeholder="请输入打扫备注"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cleaningRemarkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCleaningRemark">确认</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>

<script>
import mixin from "@/mixins/page.js";

export default {
  mixins: [mixin],
  data() {
    return {
      // 获取数据地址
      url_get_list: "~/api/room_cleaning/get_list?like=0",
      url_del: "~/api/room_cleaning/del?",
      // 字段ID
      field: "room_cleaning_id",
      url_upload: "~/api/room_cleaning/upload/img?",
      // 查询
      query: {
        "size": 7,
        "page": 1,
        "name_of_homestay": "",
        "location_of_homestay": "",
        "login_time": "",
        "create_time": "",
        "orderby": `create_time desc`
      },
      // 数据
      list: [],
      // 用户列表
      list_user_business_user: [],
      // 用户列表
      list_user_cleaning_the_user: [],
      message: '',
      cleaningRemarkDialogVisible: false, // 新增：打扫备注弹窗可见性
      cleaningRemark: '', // 新增：打扫备注内容
      currentRow: null, // 新增：当前操作的行数据
    }
  },
  methods: {
    // 修改：调整 uploadroomimg 方法签名，接收 row 参数
    uploadroomimg(param, row) {
      // 获取当前行的 room_cleaning_id
      if (row) {
        param.room_cleaning_id = row.room_cleaning_id;
      }
      this.uploadFileSub(param, "img");
    },

    // 上传文件方法
    uploadFileSub(param, key) {
      var _this = this;
      var form = new FormData(); // FormData 对象
      form.append('file', param.file); // 文件对象
      form.append('room_cleaning_id', param.room_cleaning_id); // 动态添加 room_cleaning_id 参数
      this.$upload(this.url_upload, form, function (json) {
        if (json.result) {
          // 刷新列表数据
          _this.get_list();
          _this.$toast('上传成功！', 'success');
        } else {
          _this.$toast('上传失败！');
        }
      });
    },
    clearSuccess(v) {
      let _this = this;
      let param = {"pay_state": "已查房"};
      let url = this.$toUrl(this.query, "~/api/homestay_orders/set?homestay_orders_id=" + v.homestay_orders_id);
      this.$post(url, param, function (json, status) {
        console.log("提交结果：", json);
        if (json.result) {
          _this.$toast('操作成功！', 'success');
          _this.updateState(v.room_cleaning_id);
          _this.get_list();
        } else if (json.error) {
          _this.$toast(json.error.message, 'danger');
        }
      });
    },
    updateState(id) {
      let _this = this;
      let param = {"state": "打扫完成"};
      let url = this.$toUrl(this.query, "~/api/room_cleaning/set/img?room_cleaning_id=" + id);
      this.$post(url, param, function (json, status) {
        console.log("提交结果：", json);
        if (json.result) {
          _this.get_list();
        } else if (json.error) {
          _this.$toast(json.error.message, 'danger');
        }
      });
    },
    /**
     * @description 获取到列表事件
     * @param {Object} res 响应结果
     */
    get_list_after: function get_list_after(res, func, url) {
      let _this = this
    },
    get_list_before(param) {
      var user_group = this.user.user_group;
      if (user_group != "管理员") {
        let sqlwhere = "(";
        if (user_group == "商家用户") {
          sqlwhere += "business_user = " + this.user.user_id + " or ";
        }
        if (user_group == "员工用户") {
          sqlwhere += "cleaning_the_user = " + this.user.user_id + " or ";
        }
        if (sqlwhere.length > 1) {
          sqlwhere = sqlwhere.substr(0, sqlwhere.length - 4);
          sqlwhere += ")";
          param["sqlwhere"] = sqlwhere;
        }
      }
      return param;
    },
    /**
     * 获取商家用户用户列表
     */
    async get_list_user_business_user() {
      var json = await this.$get("~/api/user/get_list?user_group=商家用户");
      if (json.result && json.result.list) {
        this.list_user_business_user = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    },
    get_user_business_user(id) {
      var obj = this.list_user_business_user.getObj({"user_id": id});
      var ret = "";
      if (obj) {
        ret = obj.nickname + "-" + obj.username;
      }
      return ret;
    },
    /**
     * 获取员工用户用户列表
     */
    async get_list_user_cleaning_the_user() {
      var json = await this.$get("~/api/user/get_list?user_group=员工用户");
      if (json.result && json.result.list) {
        this.list_user_cleaning_the_user = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    },
    get_user_cleaning_the_user(id) {
      var obj = this.list_user_cleaning_the_user.getObj({"user_id": id});
      var ret = "";
      if (obj) {
        ret = obj.nickname + "-" + obj.username;
      }
      return ret;
    },
    // 修改：点击“打扫完成”按钮时显示弹窗
    showCleaningRemarkDialog(row) {
      this.currentRow = row;
      this.cleaningRemark = ''; // 清空备注内容
      this.cleaningRemarkDialogVisible = true;
    },
    // 新增：确认打扫备注后执行后续操作
    confirmCleaningRemark() {
      if (!this.cleaningRemark.trim()) {
        this.$toast('打扫备注不能为空！', 'warning');
        return;
      }
      this.cleaningRemarkDialogVisible = false;
      // 更新打扫备注
      this.updateCleaningRemark(this.currentRow, this.cleaningRemark);
    },
    // 新增：更新打扫备注
    updateCleaningRemark(row, remark) {
      let _this = this;
      let param = {"cleaning_remarks": remark, "state": "打扫完成"};
      let url = this.$toUrl(this.query, "~/api/room_cleaning/set?room_cleaning_id=" + row.room_cleaning_id);
      this.$post(url, param, function (json, status) {
        console.log("提交结果：", json);
        if (json.result) {
          _this.$toast('打扫备注更新成功！', 'success');
          _this.clearSuccess(row); // 执行后续操作
        } else if (json.error) {
          _this.$toast(json.error.message, 'danger');
        }
      });
    },
  },
  created() {
    this.get_list_user_business_user();
    this.get_list_user_cleaning_the_user();
  }
}
</script>

<style type="text/css">
.bg {
  background: white;
}

.form.p_4 {
  padding: 1rem;
}

.form .el-input {
  width: initial;
}

.mt {
  margin-top: 1rem;
}

.text_center {
  text-align: center;
}

.float-right {
  float: right;
}

.modal_wrap {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999999999;
}

.modal_wrap .modal_box {
  width: 400px;
  height: auto;
  background: url("../../assets/modal_bg.jpg") no-repeat center;
  background-size: cover;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -200px;
  margin-top: -100px;
  border-radius: 10px;
  padding: 10px;
}

.modal_wrap .modal_box .modal_box_close {
  font-size: 20px;
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.modal_wrap .modal_box .modal_box_title {
  text-align: center;
  font-size: 18px;
  margin: 16px auto;
  color: #fff;
  border-bottom: 1px solid rgba(117, 116, 116, 0.5);
  padding-bottom: 16px;
  width: 356px;
}

.modal_wrap .modal_box .modal_box_text {
  text-align: center;
  font-size: 14px;
  color: #fff;
  margin: 5px auto;
  width: 90%;
}

.modal_wrap .modal_box .btn_box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 42px;
  margin-bottom: 20px;
}

.modal_wrap .modal_box .btn_box span {
  display: inline-block;
  width: 80px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #ccc;
  font-size: 14px;
  cursor: pointer;
  color: #fff;
}

.modal_wrap .modal_box .btn_box span:nth-child(2) {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
  margin-left: 15px;
}

.el-date-editor .el-range-separator {
  width: 10% !important;
}

.upload-btn {
  display: inline-block;
  margin: 5px !important;
}

/* 新增：隐藏文件输入框 */
.upload-input {
  display: none;
}

/* 新增：限制图片大小并保持比例 */
.table-img {
  width: 50px; /* 减小固定宽度 */
  height: 50px; /* 减小固定高度 */
  object-fit: cover; /* 确保图片比例不失真 */
  cursor: pointer; /* 添加鼠标指针样式 */
}

/* 修改：添加上传按钮样式 */
.el-upload {
  display: inline-block !important;
}

/* 隐藏上传列表 */
.el-upload-list {
  display: none !important;
}

/* 确保上传按钮样式正确 */
.el-upload .el-button {
  margin: 0 !important;
  display: inline-block !important;
}

/* 修改：确保按钮组样式正确 */
.view_a {
  display: flex;
  align-items: center;
  gap: 5px;
}

</style>
